package com.kason.framework.regester;

import com.alibaba.fastjson.JSONObject;
import com.kason.framework.Remote;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 卢清波
 * @date 2021/2/19 17:53
 */
public class ZookeeperRegester
{
    static CuratorFramework client;

    private static Map<String, List<Remote>> REGISTER = new HashMap<>();

    static {
        client = CuratorFrameworkFactory
                .newClient("localhost:2181", new RetryNTimes(3, 1000));
        client.start();

    }

    public static void regist(String interfaceName,Remote remote)
    {
        try
        {
            String result = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(String.format("/dubbo/service/%s/%s", interfaceName, JSONObject.toJSONString(remote)), null);
            System.out.println("zookeeper:"+result);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static List<Remote> get(String interfaceName)
    {
        List<Remote> remotes = new ArrayList<>();
        List<String> result = null;
        try
        {
            result = client.getChildren().forPath(String.format("/dubbo/service/%s", interfaceName));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        for (String urlstr : result) {
            remotes.add(JSONObject.parseObject(urlstr, Remote.class));
        }
        REGISTER.put(interfaceName, remotes);
        return remotes;
    }




}
